package com.banmao.mall.service.admin.impl;

import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.admin.goods.*;
import com.banmao.mall.model.vo.admin.goods.*;
import com.banmao.mall.service.admin.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;


    @Value("${myimage.baseURL}")
    private String imageBaseUrl;

    @Override
    public GoodsListVO goodsList(GoodsListBO goodsListBO) {

        PageHelper.startPage(goodsListBO.getPage(), goodsListBO.getLimit());

        // 查所有商品信息
        List<GoodsVO> goodsVOList = goodsMapper.selectAll(goodsListBO);

        // 获取分页信息
        PageInfo<GoodsVO> goodsVOPageInfo = new PageInfo<>(goodsVOList);
        long total = goodsVOPageInfo.getTotal();

        for (GoodsVO goodsVO : goodsVOList) {
            if (goodsVO.getPicUrl() != null) {
                String picUrl = goodsVO.getPicUrl();
                if(!picUrl.startsWith("http")) {
                    goodsVO.setPicUrl(imageBaseUrl + picUrl);
                }
            }
            if(goodsVO.getGallery() != null) {
                for (int i = 0; i < goodsVO.getGallery().length; i++) {
                    String gallery = goodsVO.getGallery()[i];
                    if (!gallery.startsWith("http")) {
                        gallery = imageBaseUrl + gallery;
                        goodsVO.getGallery()[i] = gallery;
                    }
                }
            }
        }

        GoodsListVO goodsListVO = new GoodsListVO();
        goodsListVO.setTotal(total);
        goodsListVO.setItems(goodsVOList);

        return goodsListVO;
    }

    @Override
    public CatAndBrandVO catAndBrand() {

        // 获取类目
        List<CategoryVO> categoryVOS = categoryMapper.selectValueAndLabelL1();
        for (CategoryVO categoryVO : categoryVOS) {
            // 根据一级类目获取二级类目
            List<CategoryChildrenVO> categoryChildrenVO = categoryMapper.selectValueAndLabelL2(categoryVO.getValue());

            categoryVO.setChildren(categoryChildrenVO);
        }

        // 获取品牌商
        List<BrandVO> brandVOS = brandMapper.selectValueAndLabel();

        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        catAndBrandVO.setCategoryList(categoryVOS);
        catAndBrandVO.setBrandList(brandVOS);

        return catAndBrandVO;
    }

    @Override
    public int goodsCreate(GoodsDetailBO goodsDetailBO) {

        // 添加商品
        GoodsBO goods = goodsDetailBO.getGoods();
        if(goods.getPicUrl() != null) {
            goods.setPicUrl(goods.getPicUrl().replace(imageBaseUrl, ""));
        }
        String[] galleries = goods.getGallery();
        if(galleries != null) {
            for (int i = 0; i < galleries.length; i++) {
                galleries[i] = galleries[i].replace(imageBaseUrl, "");
            }
            goods.setGallery(galleries);
        }
        int result = goodsMapper.insertGoods(goods);
        if(result == 0) {
            throw new RuntimeException("插入失败");
        }

        // 获取回传的主键
        Integer goodsId = goods.getId();

        // 添加商品ID和产品
        List<ProductBO> products = goodsDetailBO.getProducts();
        for (ProductBO product : products) {
            if(product.getUrl() != null) {
                product.setUrl(product.getUrl().replace(imageBaseUrl, ""));
            }

            result = goodsProductMapper.insertProduct(goodsId, product);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        // 添加规格
        List<SpecificationBO> specifications = goodsDetailBO.getSpecifications();
        for (SpecificationBO specification : specifications) {
            if(specification.getPicUrl() != null) {
                specification.setPicUrl(specification.getPicUrl().replace(imageBaseUrl, ""));
            }

            result = goodsSpecificationMapper.insertSpec(goodsId, specification);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        // 添加参数
        List<AttributeBO> attributes = goodsDetailBO.getAttributes();
        for (AttributeBO attribute : attributes) {
            result = goodsAttributeMapper.insertAttribute(goodsId, attribute);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        return result;
    }

    @Override
    public GoodsDetailVO goodsDetail(Integer goodsId) {

        // 获取商品信息
        GoodsVO goodsVO = goodsMapper.selectByGoodsID(goodsId);
        String picUrl = goodsVO.getPicUrl();
        if(picUrl != null) {
            if(!picUrl.startsWith("http")) {
                goodsVO.setPicUrl(imageBaseUrl + picUrl);
            }
        }
        String[] gallery = goodsVO.getGallery();
        if (gallery != null) {
            for (int i = 0; i < gallery.length; i++) {
                if(!gallery[i].startsWith("http")) {
                    gallery[i] = imageBaseUrl + gallery[i];
                }
            }
        }
        goodsVO.setGallery(gallery);

        // 获取类目信息
        // 根据子类目查一级类目ID
        Integer categoryL1 = categoryMapper.selectCateIDL2(goodsVO.getCategoryId());
        Integer categoryL2 = goodsVO.getCategoryId();

        // 获取参数信息
        List<AttributeVO> attributeVOS = goodsAttributeMapper.selectAttByGoodsID(goodsId);

        // 获取规格信息
        List<SpecificationVO> specificationVOS = goodsSpecificationMapper.selectSpecByGoodsID(goodsId);
        for (SpecificationVO specificationVO : specificationVOS) {
            String specPicUrl = specificationVO.getPicUrl();
            if(specPicUrl != null) {
                if(!specPicUrl.startsWith("http")) {
                    specificationVO.setPicUrl(imageBaseUrl + specPicUrl);
                }
            }
        }

        // 获取产品信息
        List<ProductVO> productVOS = goodsProductMapper.selectProductByGoodsID(goodsId);
        for (ProductVO productVO : productVOS) {
            String url = productVO.getUrl();
            if(url != null) {
                if(!url.startsWith("http")) {
                    productVO.setUrl(imageBaseUrl + url);
                }
            }
        }


        // 封装结果
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        goodsDetailVO.setCategoryIds(new Integer[]{categoryL1, categoryL2});
        goodsDetailVO.setGoods(goodsVO);
        goodsDetailVO.setAttributes(attributeVOS);
        goodsDetailVO.setSpecifications(specificationVOS);
        goodsDetailVO.setProducts(productVOS);

        return goodsDetailVO;
    }

    @Override
    public int goodsUpdate(GoodsDetailBO goodsDetailBO) {

        // 根据商品ID更改goods表
        GoodsBO goods = goodsDetailBO.getGoods();
        if(goods.getPicUrl() != null) {
            goods.setPicUrl(goods.getPicUrl().replace(imageBaseUrl, ""));
        }
        String[] galleries = goods.getGallery();
        if(galleries != null) {
            for (int i = 0; i < galleries.length; i++) {
                galleries[i] = galleries[i].replace(imageBaseUrl, "");
            }
            goods.setGallery(galleries);
        }
        int result = goodsMapper.updateGoodsByGoodsID(goods);
        if(result == 0) {
            throw new RuntimeException("插入失败");
        }

        // 根据参数ID删除attribute表中的记录，然后再添加
        List<AttributeBO> attributes = goodsDetailBO.getAttributes();
            goodsAttributeMapper.deleteAllByGoodsID(goods.getId());

        for (AttributeBO attribute : attributes) {
            // 物理删除
            result = goodsAttributeMapper.deleteByPrimaryKey(attribute.getId());

            attribute.setGoodsId(goods.getId());
            result = goodsAttributeMapper.insertAttrWithUpdate(attribute);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        // 根据规格ID删除specification表的记录，然后再添加
        List<SpecificationBO> specifications = goodsDetailBO.getSpecifications();
            // 删除全部规格
            result = goodsSpecificationMapper.deleteAllByGoodsID(goods.getId());
        for (SpecificationBO specification : specifications) {
            // 物理删除
            result = goodsSpecificationMapper.deleteByPrimaryKey(specification.getId());

            // 替换图片路径前缀
            if(specification.getPicUrl() != null) {
                specification.setPicUrl(specification.getPicUrl().replace(imageBaseUrl, ""));
            }

            specification.setGoodsId(goods.getId());
            result = goodsSpecificationMapper.insertSpecWithUpdate(specification);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        // 根据产品ID删除product表中的记录，然后再添加
        List<ProductBO> products = goodsDetailBO.getProducts();
            // 删除全部产品
            goodsProductMapper.deleteAllByGoodsID(goods.getId());

        for (ProductBO product : products) {
            // 物理删除
            result = goodsProductMapper.deleteByPrimaryKey(product.getId());

            // 处理图片路径前缀
            if(product.getUrl() != null) {
                product.setUrl(product.getUrl().replace(imageBaseUrl, ""));
            }

            product.setGoodsId(goods.getId());
            result = goodsProductMapper.insertProductWithUpdate(product);
            if(result == 0) {
                throw new RuntimeException("插入失败");
            }
        }

        return result;
    }

    @Override
    public int goodsDelete(GoodsBO goodsBO) {

        int result = goodsMapper.updateDeletedByID(goodsBO.getId());
        if(result == 0) {
            throw new RuntimeException("SQL出问题啦！");
        }

        return result;
    }
}
